package cn.letao;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private ImageView image;
    private Button btn;
    private int img[] = {R.drawable.b1, R.drawable.b2, R.drawable.b3, R.drawable.b4, R.drawable.b5,};
    private int index = 0;
    private Handler handler;        //消息头
    private final int Mes_CHANGE_B1 = 10001;
    //是否处于暂停状态
    private Boolean isPause = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.tip);
        textView.setTextColor(Color.BLUE);

        image = findViewById(R.id.image);
        image.setImageResource(R.drawable.b1);

        btn = findViewById(R.id.btn);

        handler = new Handler(new Handler.Callback() {
            //主线程接收子线程发出的消息
            public boolean handleMessage(Message message) {
                if (message.what == Mes_CHANGE_B1) {
                    index = (index + 1) % img.length;
                    image.setImageResource(img[index]);
                    btn.setText(R.string.stop);
                    btn.setTextColor(Color.RED);
                    return true;
                }
                return false;
            }
        });

        //自动切换图片
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (!isPause) {
                        //子线程不能直接修改主线程创建的view，必须要通过消息机制告诉主线程更新
                        //子线程使用handler将消息发向主线程
                        Message message = new Message();
                        message.what = Mes_CHANGE_B1;
                        handler.sendMessage(message);
                    }
                }
            }
        }).start();

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             isPause = !isPause;
             btn.setText(R.string.start);
             btn.setTextColor(Color.BLACK);
            }
        });
    }
}
